package com.black.cat.seed.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.black.cat.seed.common.ApiResponse;
import com.black.cat.seed.entity.User;
import com.black.cat.seed.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author blackcat
 * @create 2021/4/4 15:52
 * @version: 1.0
 * @description:用户模块
 */
@RestController
@RequestMapping("/api/account")
public class AccountController  {

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder encrypt;

    @GetMapping("/get")
    public ApiResponse<User> get(Long id) {
        return ApiResponse.ofSuccess(userService.getById(id));
    }

    @PostMapping("page")
    public ApiResponse<IPage<User>> page(User entity, Integer pageNo, Integer pageSize) {
        IPage<User> page = new Page<>(pageNo, pageSize);
        return ApiResponse.ofSuccess(userService.page(page, new QueryWrapper<>(entity)));
    }

    @PostMapping("create")
    public ApiResponse<Boolean> create(User entity) {
        entity.setPassword(encrypt.encode(entity.getPassword()));
        return ApiResponse.ofSuccess(userService.save(entity));
    }

    @PostMapping("update")
    public ApiResponse<Boolean> update(@Validated() User entity) {
        if(StringUtils.isNotBlank(entity.getPassword())){
            entity.setPassword(encrypt.encode(entity.getPassword()));
        }
        return ApiResponse.ofSuccess(userService.updateById(entity));
    }

    @PostMapping("/delete")
    public ApiResponse<Boolean> delete(Long id) {
        return ApiResponse.ofSuccess(userService.removeById(id));
    }

    @PostMapping("updatePassword")
    public ApiResponse<Boolean> updatePassword(Long id,String oldPassword,String password) {
        User org = userService.getById(id);
        if(org == null){
            throw  new RuntimeException("用户不存在");
        }
        if(!encrypt.matches(oldPassword,org.getPassword())){
            throw  new RuntimeException("密码错误");
        }
        User entity = new User();
        entity.setId(id);
        if(StringUtils.isNotBlank(password)){
            entity.setPassword(encrypt.encode(entity.getPassword()));
        }
        return ApiResponse.ofSuccess(userService.updateById(entity));
    }

}
